package com.gwcm.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gwcm.exception.BusinessException;
import com.gwcm.model.dto.menu.MenuAddRequest;
import com.gwcm.model.dto.menu.MenuDeleteRequest;
import com.gwcm.model.dto.menu.MenuQueryRequest;
import com.gwcm.model.dto.menu.MenuUpdateRequest;
import com.gwcm.model.dto.role.RoleQueryRequest;
import com.gwcm.model.entity.Menu;
import com.gwcm.model.entity.Role;
import com.gwcm.model.vo.MenuVo;
import com.gwcm.model.vo.RoleVo;
import com.gwcm.service.IMenuService;
import com.yhz.commonutil.common.BaseResponse;
import com.yhz.commonutil.common.ErrorCode;
import com.yhz.commonutil.common.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/menu")
@Api(tags = "菜单接口")
public class MenuController {
    @Resource
    private IMenuService menuService;

    @ApiOperation("参数查询菜单列表")
    @PreAuthorize("hasAuthority('system:menu:list')")
    @GetMapping("/list")
    public BaseResponse list(Menu menu){
        List<Menu> list = menuService.selectMenuList(menu);
        return ResultUtils.success(list);
    }

    @ApiOperation("获取所有目录+菜单")
    @PreAuthorize("hasAuthority('system:menu:list')")
    @GetMapping("/tree")
    public BaseResponse tree(){
        List<Menu> list = menuService.selectAllMenuTree();
        return ResultUtils.success(list);
    }

    @ApiOperation("通过menuId查询menu")
    @GetMapping("/{menuId}")
    public BaseResponse getById(@PathVariable("menuId") Long menuId){
        return ResultUtils.success(menuService.selectMenuById(menuId));
    }

    @ApiOperation("添加菜单")
    @PostMapping("/save")
    public BaseResponse addMenu(@RequestBody MenuAddRequest menuAddRequest){
        Menu menu = new Menu();
        BeanUtils.copyProperties(menuAddRequest, menu);
        menuService.saveMenu(menu);
        return ResultUtils.success();
    }

    @ApiOperation("修改菜单")
    @PostMapping("/update")
    public BaseResponse updateMenu(@RequestBody MenuUpdateRequest menuUpdateRequest) {
        Menu menu = new Menu();
        BeanUtils.copyProperties(menuUpdateRequest, menu);
        menuService.updateMenu(menu);
        return ResultUtils.success();
    }

    @ApiOperation("删除菜单")
    @DeleteMapping("/delete")
    public BaseResponse deleteMenu(@RequestBody MenuDeleteRequest menuDeleteRequest) {
        Menu menu = new Menu();
        BeanUtils.copyProperties(menuDeleteRequest, menu);
        boolean delete = menuService.removeById(menu);
        if(!delete){
            throw new BusinessException(ErrorCode.DELETE_ERROR);
        }
        return ResultUtils.success();
    }
}
